import os, sys, time, threading, yaml

from ivic.core import Utils
from ivic.core import Logging
from ivic.vprocess.Config import vprocess_config

 
logger = Logging.get_logger('ivic.vprocess.ServerMonitor')

class ServerMonitor(threading.Thread):
    
    def __init__(self, rest_url=None, cap='linux-vprocess'):   
        threading.Thread.__init__(self)
        self.url = rest_url
        self.cap = cap
        
        self.server_uuid = vprocess_config.uuid
        if self.server_uuid == None:
            self.running = False
        else:
            self.running = True
        
    def dict(self):
        try:
            info = {'uuid':self.server_uuid,
                    'status':'running',
                    'timestamp':time.strftime("%Y-%m-%d %X", time.localtime(time.time())),
                    'capability':self.cap}
            return info
        except Exception, e:
            logger.error("%s" % e)
            return {}
        
    def serialize(self, info=None):
        try:
            message = ""
            for key, value in info.items():
                message += "%s=%s&" % (key, value)
            return message[:-1]
        except Exception, e:
            logger.error("%s" % e)
            return ''
    def report(self):
        try:
            url = self.url
            message = self.serialize(self.dict())
            try:
                command = "curl -X POST -d \"%s\" -H \"Accept: text/xml\" %s" % (message, url)
                os.system(command)
                logger.debug(command)
            except Exception, e:
                logger.error("server-monitor: %s" % e) 
                    #sleep 90 seconds and then do the reporting    
        except Exception, e:
            logger.error("server-monitor: %s" % e)
                      
    def run(self):
        try:
            while self.running:
                try:
                    self.report()
                    #sleep 90 seconds and then do the reporting
                    time.sleep(90)    
                except Exception, e:
                    logger.error("server-monitor: %s" % e)
        except Exception, e:
            self.running = False
            logger.error("server-monitor: %s" % e)
                
    def stop(self):
        self.running = False 
        
